package test04.syn;

public class MyRunnable implements Runnable {

    private int ticket = 50;

    // private String lock = "";
    // private final Object lock = new Object();
    private Class<?> lock = Object.class;
    @Override
    public void run() {
        // 注意锁的临界区范围 - 否则别的线程没有机会进来！！
        while (true) {
            synchronized (Object.class) {
                if (ticket <= 0) {
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String name = Thread.currentThread().getName();
                System.out.printf("%s 出售了第 %d 张电影票！%n", name, ticket);
                ticket -- ;
            }
        }
    }
}
